package mediator;

import guiWindows.GUITemplatesSelector;
import guiWindows.MainWindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import objectTemplate.Template;
import objectsDiagram.Fluent;
import objectsDiagram.Task;

public class TemplateMediator implements ActionListener, TreeSelectionListener {
	private GUITemplatesSelector guiTemplatesSelector;
	private LinkedList<Template> mainGroupTemplate;
	private Vector<Task> vectorTask;
	private Template currentTemplate;
	private MainWindow mainWindow;
	private Integer enablerButtonInt = new Integer(0);
	private LinkedList<GUITemplatesSelector.TaskPanel> listTaskPanel;
	private LinkedList<Fluent> listFluents;

	public TemplateMediator(Vector<Task> newVectorTask, LinkedList<Fluent> listFluents, MainWindow newMainWindow){
		this.mainGroupTemplate = new LinkedList<Template>();
		this.guiTemplatesSelector = new GUITemplatesSelector();
		this.guiTemplatesSelector.setTreeSellectionListener(this);
		this.guiTemplatesSelector.setListenerButtons(this);
		this.guiTemplatesSelector.getOkButton().setEnabled(false);
		this.mainWindow = newMainWindow;
		this.vectorTask = newVectorTask;
		this.listFluents = listFluents;
		parseTemplates();
	}

	public void show(){
		this.guiTemplatesSelector.setVisible(true);
	}

	public void parseTemplates(){

		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			File templateProperties = new File("templates.properties");
			Document document = db.parse(templateProperties);
			document.getDocumentElement().normalize();
			NodeList listTemplates = document.getElementsByTagName("template");
			for(int i=0; i<listTemplates.getLength();i++){
				Node nodeTemplate = listTemplates.item(i);
				Element elementTemplate = (Element)nodeTemplate;

				NamedNodeMap namedMapTemplate = elementTemplate.getAttributes();
				Node idAttr = namedMapTemplate.getNamedItem("id");
				int id = Integer.parseInt(idAttr.getNodeValue());

				Node textAttr = namedMapTemplate.getNamedItem("text");
				String text = textAttr.getNodeValue();

				Node descriptionAttr = namedMapTemplate.getNamedItem("description");
				String description = descriptionAttr.getNodeValue();

				Node displayAttr = namedMapTemplate.getNamedItem("display");
				String display = displayAttr.getNodeValue();

				Node nameAttr = namedMapTemplate.getNamedItem("name");
				String name = nameAttr.getNodeValue();

				Node numberBranchAttr = namedMapTemplate.getNamedItem("numberBranch");
				int numberBranch = Integer.parseInt(numberBranchAttr.getNodeValue());

				Node imageAttr = namedMapTemplate.getNamedItem("image");
				String image = imageAttr.getNodeValue();
				Template template = new Template(id,description,display,name,text,numberBranch,new ImageIcon(image));
				this.mainGroupTemplate.add(template);
				this.guiTemplatesSelector.add(mainGroupTemplate);
			}
			this.guiTemplatesSelector.loadTemplate();
		} catch (ParserConfigurationException e) {
			JOptionPane.showMessageDialog(this.guiTemplatesSelector, "ERROR \nCould not open \"templates.properties\" file");
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this.guiTemplatesSelector, "ERROR \nCould not exists \"templates.properties\" file in the directory");
		}
	}

	public void actionPerformed(ActionEvent e) {
		if(this.listTaskPanel != null){
			for(int i=0;i<this.listTaskPanel.size();i++){
				if(this.listTaskPanel.get(i).getTaskButton()==e.getSource()){
					SelectActivityMediator selectTemplateMediator = new SelectActivityMediator(this.listTaskPanel.get(i).getTaskField(),vectorTask,this);
					selectTemplateMediator.show();
					break;
				}
				if(this.listTaskPanel.get(i).getFluentButton()==e.getSource()){
					SelectActivityMediator selectTemplateMediator = new SelectActivityMediator(this.listTaskPanel.get(i).getTaskField(),listFluents,this);
					selectTemplateMediator.show();
					break;
				}
			}
		}
		if(this.guiTemplatesSelector.getOkButton()==e.getSource()){
			this.mainWindow.getGuiCreateProperties().getAreasPanel().setVisible(false);
			this.mainWindow.getGuiCreateProperties().addNewAreaPanel().getArea().setText(completeProperties(currentTemplate));
			this.mainWindow.getGuiCreateProperties().getAreasPanel().setVisible(true);
			this.mainWindow.getGuiCreateProperties().getDeleteButton().setEnabled(true);
			this.mainWindow.getGuiCreateProperties().getCheckPropertyButton().setEnabled(true);
			this.guiTemplatesSelector.setVisible(false);
			this.guiTemplatesSelector.dispose();
		}
		if(this.guiTemplatesSelector.getCancelButton()==e.getSource()){
			this.guiTemplatesSelector.setVisible(false);
			this.guiTemplatesSelector.dispose();
		}
	}

	@Override
	public void valueChanged(TreeSelectionEvent e) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)guiTemplatesSelector.getJTree().getLastSelectedPathComponent();
		if(node!=null){	
			Object nodeInfo = node.getUserObject();
			if (node.isLeaf()) {
				String templateString = (String)nodeInfo;
				for(int i =0;i<mainGroupTemplate.size();i++){
					if(mainGroupTemplate.get(i).getName().compareTo(templateString)==0){
						this.guiTemplatesSelector.getOkButton().setEnabled(false);
						this.guiTemplatesSelector.clearGUITemplate();
						this.currentTemplate = this.mainGroupTemplate.get(i);
						this.enablerButtonInt = this.currentTemplate.getNumberBranch(); 
						this.guiTemplatesSelector.loadTemplateInPanel(this.currentTemplate);
						this.listTaskPanel = this.guiTemplatesSelector.getListTaskPanel();
						for(int j=0;j<this.listTaskPanel.size();j++){
							this.listTaskPanel.get(j).getTaskField().setText("");
							if(listFluents.isEmpty()){
								this.listTaskPanel.get(j).getFluentButton().setEnabled(false);
							}
						}
						this.guiTemplatesSelector.setListenerTaskButtons(this);
						break;
					}
				}
			}
		}
	}

	public Integer getEnablerButtonInt(){
		return this.enablerButtonInt;
	}

	public void setEnablerButtonInt(int newValue){
		this.enablerButtonInt = new Integer(newValue);
	}

	public GUITemplatesSelector getGuiTemplatesSelector(){
		return this.guiTemplatesSelector;
	}

	public String completeProperties(Template newTemplate){
		int numberBranch = newTemplate.getNumberBranch();
		String property = newTemplate.getText();
		for(int i=0;i<numberBranch;i++){
			if(!isFluent(this.listTaskPanel.get(i).getTaskField().getText())){
				property = property.replaceAll(String.valueOf(((char)(i+65))), this.listTaskPanel.get(i).getTaskField().getText().toLowerCase());
			}else{
				property = property.replaceAll(String.valueOf(((char)(i+65))), this.listTaskPanel.get(i).getTaskField().getText());
			}
		}		
		return property;
	}

	private boolean isFluent(String idFluent){
		for(Fluent f:listFluents){
			if(f.getId().equals(idFluent)){
				return true;
			}
		}
		return false;
	}
}
